# -*- coding: utf-8 -*-
"""
@Time : 2023/7/28 15:57
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : update_book_valid.py
"""

import sys
from flask_restful import Resource, reqparse

from service.mysql_connect import MySQLConnected
from service.config_import import load_yaml

sys.path.append('..')

parser = reqparse.RequestParser()
parser.add_argument('book_id', type=int, help="参数book_id不能为空", required=True)


class UpdateBookValid(Resource):
    def post(self):
        args = parser.parse_args()
        update_book_id = args.get('book_id')
        yaml_config_path = "config_info.yaml"
        params = load_yaml(yaml_config_path)
        dbinfo = params['databases']['library_db_info']
        # print(dbinfo)
        db = params['databases']['library_db_name']
        connected = MySQLConnected(dbinfo)
        sql_for_book_status = "select status from " + db + ".books where id = %s"
        connected.cur.execute(sql_for_book_status, str(update_book_id))
        book_status = connected.cur.fetchall()
        if not book_status:
            return {'content': '不存在对应书籍，请确认', 'result': 'failure'}
        for b_s in book_status:
            book_sta, = b_s
        if book_sta == 0:
            return {'content': '该书现未归还，不能切换书籍状态', 'result': 'failure'}
        sql = "update " + db + ".books set valid = not valid where id = %s"
        connected.cur.execute(sql, str(update_book_id))

        connected.con.commit()
        connected.cur.close()
        connected.con.close()

        return {'content': "书籍状态更新成功", 'result': 'success'}
